const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const adminindex = require('./routes/admin/index')
const adminusers = require('./routes/admin/users')
const consumerindex = require('./routes/consumer/index')
const consumerusers = require('./routes/consumer/users')
const headEndindex = require('./routes/headEnd/index')
const headEndusers = require('./routes/headEnd/users')
const headEndlogin = require('./routes/headEnd/login')
const storeindex = require('./routes/store/index')
const storelogin = require('./routes/store/login')
const storeusers = require('./routes/store/users')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

// app.use(views(__dirname + '/views', {
//   extension: 'ejs'
// }))

const path = require('path')
const render = require('koa-art-template');
render(app, {
  root: path.join(__dirname, 'views'),
  extname: '.html',
  debug: process.env.NODE_ENV !== 'production'
});

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(adminindex.routes(), adminindex.allowedMethods())
app.use(adminusers.routes(), adminusers.allowedMethods())
app.use(consumerindex.routes(), consumerindex.allowedMethods())
app.use(consumerusers.routes(), consumerusers.allowedMethods())
app.use(headEndindex.routes(), headEndindex.allowedMethods())
app.use(headEndusers.routes(), headEndusers.allowedMethods())
app.use(headEndlogin.routes(), headEndlogin.allowedMethods())
app.use(storelogin.routes(), storelogin.allowedMethods())
app.use(storeindex.routes(), storeindex.allowedMethods())
app.use(storeusers.routes(), storeusers.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
